﻿
package com.hh.bss.util;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;




/**
 * <p>Title: 基于XML文件的属性管理器</p>
 * <p>Description: </p>
 * @version 1.2
 */
public class XMLPropertyManager implements PropertyManager{
	private static final Log logger = LogFactory.getLog(XMLPropertyManager.class);
	/**
	 * 默认属性文件为classes根目录下的properties.xml
	 */
	private final String DEFAULT_FILE_NAME = "properties.xml";
	private String fullFileName = null;
	//属性值集合
	private HashMap properties = null;
	public String getProperty(String name){
		String value =(String)properties.get(name);
		return value;
	}
	/**
	 * @param fileName String : 文件须在classes根目录下
	 * 文件格式如下所示：
	 * <?xml version="1.0"?> 
	 *  <properties> 
	 *    <property key="name1" value="value1"/>
	 *    <property key="name2">value2</property>
	 *    <property key="namen" value="valuen"/>
	 *  </properties>  
	 */	
	public XMLPropertyManager(final String fileName){
		this.fullFileName = fileName;
	}
	/**
	 * 读取指定的属性文件
	 * @param fileName String : 属性文件名（此文件需放在classes根目录下）
	 * @param load boolean : 如果为true，则在构建对象时直接读入所有的属性设置
	 */
	public XMLPropertyManager(final String fileName, final boolean load){
		this.fullFileName = fileName;
		if(load == true) this.load();
	}
	public XMLPropertyManager(){
		this.fullFileName = this.DEFAULT_FILE_NAME;
	}
	public synchronized void load(){
		logger.info("configurating from file:"+fullFileName);
		this.properties = new HashMap();
		try{
	    	SAXReader reader = new SAXReader();
	    	Document document = reader.read(XMLPropertyManager.class.getResourceAsStream("/"+this.fullFileName));			
			if(document == null) return;
			Element root = document.getRootElement();
			for(Iterator it = root.elementIterator("property");it.hasNext();){
				Element property = (Element)it.next();
				Property pair = DOM4JHelper.getProperty(property);
				if(pair == null) continue;
				properties.put(pair.getName(),pair.getValue());
			}
		}catch(DocumentException de){
			logger.error("load():"+de.getMessage());
		}
	}
	//
	public void setProperty(String name,String value){
		logger.info("do not implement!");
	}
	public void setProperty(String name,String value,boolean sync){
		logger.info("do not implement!");
	}
	public void store(){
		logger.info("do not implement!");
	};
	
}
